package com;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;

public class Service {
    private String id;
    private int num;
    public Service(String id,int num){
        this.id=id;
        this.num=num;
    }
    //控制单元
    public void service(){
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        String valus = jedis.get("userId:" + id);
        try {
        if (valus==null){
            jedis.setex("userId:"+id,10,Long.MAX_VALUE-num+"");//意思是最多调用10次，处理方法是抛出异常，+“”是因为他要字符串
            System.out.println("为空啊");
        }else {
                Long val= jedis.incr("userId:"+id);
                System.out.print("ddd");
                business(id,num-(Long.MAX_VALUE-val));
            }
        } catch (JedisDataException e) {
                System.out.println("你用完次数了");
                return;
            } finally {
                jedis.close();
            }

    }

    //业务操作
    public void business(String id,Long val){
        System.out.println("用户："+id+"业务执行第"+val+"次");
    }



        public static void main(String[] args) {
            MyThread mt1=new MyThread("用户1",10);
            MyThread mt2=new MyThread("用户2",30);
            mt1.start();
            mt2.start();
        }

}

class MyThread extends Thread{
    Service sc ;
    public MyThread(String id,int num){
        sc= new Service(id,num);

    }
    @Override
    public void run(){
        while (true){
            sc.service();
            try {
                Thread.sleep(500L);//上面存活时间10，这里如果设置成一秒，1*10刚好等于10，这样到时候就相当于重置了
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
